//
//  HttpClient.m
//  JMZGO
//
//  Created by apple  on 17/7/18.
//  Copyright © 2017年 JMZ. All rights reserved.
//

#import "HttpClient.h"

@implementation HttpClient


+ (instancetype)sharedInstance
{
    static HttpClient *client;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        client = [[HttpClient alloc] init];
    });
    return client;
}

+ (void)postWithURL:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    // 1.创建请求管理对象
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    // 2.服务器告诉客户端，返回的是 text/html类型的数据，不然会报code=1016的错误，但是AFN默认只支持JSON和xml，并不支持这种普通的文本格式。
    //    // mgr.responseSerializer为设置服务器返回的类型。默认情况下为：mgr.responseSerializer=[AFJSONRequestSerializer serializer];
    //    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    //    // mgr.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"text/plain", @"text/json", @"application/json", @"text/javascript", nil];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    mgr.requestSerializer = [AFHTTPRequestSerializer serializer];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 3.发送请求
    [mgr POST:url parameters:params
      success:^(NSURLSessionDataTask *task, id responseObject) {
          if (success) {
              success(responseObject);
          }
      } failure:^(NSURLSessionDataTask *task, NSError *error) {
          if (failure) {
              failure(error);
          }
      }];
    
}

- (void)request:(NSString *)url
         params:(NSDictionary *)params
        success:(void(^)(NSObject *response))success
        failure:(void(^)(NSError *error))failure
{
//    [self.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",@""]  forHTTPHeaderField:@"Authorization"];
    
    //添加SSL证书验证
//    [self setSecurityPolicy:[self customSecurityPolicy]];
    
    self.requestSerializer.timeoutInterval = 20.f;
    self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"application/x-www-form-urlencoded",@"text/html",@"text/xml",@"text/plain", nil];//,@"application/soap+xml"
    
    
    [self POST:url parameters:params progress:nil success:^(NSURLSessionDataTask *task, id response){
        success(response);
    } failure:^(NSURLSessionDataTask *take, NSError *error){
        failure(error);
    }];

}

+ (void)requestJson:(NSString *)url
             params:(NSDictionary *)params
            success:(void(^)(NSDictionary *data))success
            failure:(void(^)(NSError *error))failure
{
    if (!params)
        params = [NSMutableDictionary new];
    
    [[self sharedInstance] request:url params:params
                           success:^(NSObject *response){
                               NSDictionary *dict = (NSDictionary *)response;
                        
                               success(dict);
                           }
                           failure:failure];

}

- (void)requestPost:(NSString *)url
             params:(NSDictionary *)params
            success:(void(^)(id response))success
            failure:(void(^)(NSError *error))failure
{
    self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"application/x-www-form-urlencoded",@"application/soap+xml",@"text/html",@"text/plain", nil];
    self.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [self POST:url parameters:params progress:nil success:^(NSURLSessionDataTask *task, id response){
        success(response);
    } failure:^(NSURLSessionDataTask *take, NSError *error){
        failure(error);
    }];
}
/**
 * POST请求获取返回值不是JSon数据
 */
+ (void)requestPost:(NSString *)url
             params:(NSDictionary *)params
            success:(void(^)(NSInteger result))success
            failure:(void(^)(NSError *error))failure
{
    if (!params)
        params = [NSMutableDictionary new];
    
    [[self sharedInstance] requestPost:url params:params
                           success:^(id response){
                               NSString * resultStr=[[NSString alloc] initWithData:response encoding:NSASCIIStringEncoding];
                               NSInteger result = [resultStr integerValue];
                               success(result);
                           }
                           failure:failure];

}

- (void)requestGet:(NSString *)url
            params:(id)params
           success:(void(^)(id response))success
           failure:(void(^)(NSError *error))failure
{
    self.requestSerializer.timeoutInterval = 10.f;
    self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", nil];
    
    self.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [self GET:url parameters:params progress:nil success:^(NSURLSessionDataTask *task, id response){
        success(response);
    } failure:^(NSURLSessionDataTask *take, NSError *error){
        failure(error);
    }];
}

+ (void)requestGet:(NSString *)url
            params:(id)params
           success:(void(^)(id response))success
           failure:(void(^)(NSError *error))failure
{
    if (!params)
        params = [NSMutableDictionary new];
    
    [[self sharedInstance] requestGet:url params:params
                           success:^(id response){
                               success(response);
                           }
                           failure:failure];
}

//支持https
- (AFSecurityPolicy *)customSecurityPolicy
{
    //先导入证书，找到证书的路径
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"citywifi" ofType:@"cer"];
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    
    //AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    //allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    //如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = NO;
    NSSet *set = [[NSSet alloc] initWithObjects:certData, nil];
    securityPolicy.pinnedCertificates = set;
    
    return securityPolicy;
}

@end
